<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">+新增</el-button>
    <el-form :inline="true" :model="config">
      <el-form-item label="请输入">
        <el-input
          v-model="config.keyword"
          placeholder="请输入用户名"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSerch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="list" style="width: 100%" height="500">
      <el-table-column prop="id" label="编号" width="120" />
      <el-table-column prop="name" label="名称" width="120" />
      <el-table-column prop="age" label="年龄" width="120" />
      <el-table-column prop="gender" label="性别" width="120" />
      <el-table-column prop="birthday" label="生日" width="300" />
      <el-table-column prop="address" label="地址" width="600" />
      <el-table-column prop="" label="操作" width="">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            @click="deleteUser(scope.row.id)"
            type="danger"
            size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small
      background
      layout="prev, pager, next"
      :total="pageTotal"
      class="mt-4 pager"
      @change="changePageIndex"
    />
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="35%"
    :before-close="handleClose"
  >
    <el-form :inline="true" :model="formUser" ref="userForm">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="姓名"
            prop="name"
            :rules="[{ required: true, message: '姓名必填' }]"
          >
            <el-input v-model="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="年龄"
            prop="age"
            :rules="[
              { required: true, message: '年龄必填' },
              { type: 'number', message: '年龄必须是数字' },
            ]"
          >
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="性别"
            prop="gender"
            :rules="[{ required: true, message: '性别必填' }]"
          >
            <el-select
              v-model="formUser.gender"
              placeholder="请选择性别"
              style="width: 200px"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="出身日期"
            prop="birthday"
            :rules="[{ required: true, message: '出身日期必填' }]"
          >
            <el-date-picker
              v-model="formUser.birthday"
              type="date"
              placeholder="请选择出身日期"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item
            label="地址"
            style="width: 400px"
            prop="address"
            :rules="[{ required: true, message: '地址必填' }]"
          >
            <el-input v-model="formUser.address" placeholder="请输入地址" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="AddOrUpdateUser"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage } from "element-plus";
import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  ref,
  reactive,
} from "vue";

export default defineComponent({
  setup() {
    const { proxy } = getCurrentInstance();
    const list = ref([]);
    const config = reactive({
      keyword: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const pageTotal = ref(0);
    onMounted(() => {
      getUserData();
    });
    const getUserData = async () => {
      let res = await proxy.$api.getUserData(config);
      list.value = res.list;
      pageTotal.value = res.totalCount;
    };
    // const changePage = async (page) => {
    //   config.pageIndex = page;
    //   let res = await proxy.$api.getUserData(config);
    //   list.value = res.list;
    //   pageTotal.value = res.totalCount;
    // };
    const changePageIndex = async (pageIndex, pageSize) => {
      config.pageIndex = pageIndex;
      config.pageSize = pageSize;
      let res = await proxy.$api.getUserData(config);
      list.value = res.list;
      pageTotal.value = res.totalCount;
    };
    const handleSerch = async () => {
      let res = await proxy.$api.getUserData(config);
      list.value = res.list;
      pageTotal.value = res.totalCount;
    };
    //控制弹出层的显示，隐藏
    const dialogVisible = ref(false);
    const handleClose = (done) => {
      ElMessageBox.confirm("确定关闭吗")
        .then(() => {
          proxy.$refs.userForm.resetFields();
          done();
        })
        .catch(() => {
          // catch error
        });
    };
    //添加用户的form数据
    const formUser = reactive({
      name: "", //用户名
      age: "",
      gender: "",
      birthday: "",
      address: "",
    });
    const timeFormat = (time) => {
      var time = new Date(time);
      var year = time.getFullYear();
      var mouth = time.getMonth() + 1;
      var day = time.getDate();
      function add(m) {
        return m < 10 ? "0" + m : m;
      }
      return year + "-" + add(mouth) + "-" + add(day);
    };
    const AddOrUpdateUser = async () => {
      //表单校验
      proxy.$refs.userForm.validate(async (valid) => {
        if (valid) {
          if (action.value == "add") {
            formUser.birthday = timeFormat(formUser.birthday);
            var res = await proxy.$api.AddUser(formUser);
            if (res) {
              ElMessage({
                showClose: true,
                message: "新增成功",
                type: "success",
              });
              //elementplus from表单自带的清除from数据方法，使用需在每个item设置好prop
              proxy.$refs.userForm.resetFields();
              dialogVisible.value = false;
              getUserData();
            }
          } else {
            let res = await proxy.$api.UpdateUser(formUser);
            if (res) {
              ElMessage({
                showClose: true,
                message: "修改成功",
                type: "success",
              });
              proxy.$refs.userForm.resetFields();
              dialogVisible.value = false;
              getUserData();
            }
          }
        } else {
          //此处只能使用单引号
          ElMessage({
            showClose: true,
            message: "请输入正确的内容",
            type: "error",
          });
        }
      });
    };
    //取消
    const handleCancel = () => {
      proxy.$refs.userForm.resetFields();
      dialogVisible.value = false;
    };
    //区分编辑和新增
    const action = ref("add");
    //编辑用户
    const handleEdit = (row) => {
      dialogVisible.value = true;
      action.value = "edit";
      //解释此处为何使用nextTick
      //nextTick 异步操作，释义为当整个页面元素dom发生变化后，下一步执行的操作
      //因此当此处dialogVisible.value = true;之后，弹出层出现，页面元素发生变化，进一步触发nextTick回调执行浅拷贝，才会对formUser进行赋值
      proxy.$nextTick(() => {
        //浅拷贝
        Object.assign(formUser, row);
      });
    };
    //新增用户
    const handleAdd = () => {
      dialogVisible.value = true;
      action.value = "add";
    };

    const deleteUser = async (id) => {
      ElMessageBox.confirm("确定删除吗").then(async () => {
        let res = await proxy.$api.DeleteUser(id);
        if (res) {
          ElMessage({
            showClose: true,
            message: "删除成功！",
            type: "success",
          });
          getUserData();
        }
      });
    };
    return {
      action,
      list,
      config,
      //changePage,
      pageTotal,
      changePageIndex,
      handleSerch,
      handleClose,
      dialogVisible,
      formUser,
      AddOrUpdateUser,
      handleCancel,
      handleAdd,
      handleEdit,
      deleteUser,
    };
  },
});
</script>
<style lang="less" scoped>
.table {
  position: relative;
  height: 520px;
  .pager {
    position: absolute;
    right: 0;
    bottom: -20px;
  }
}
.user-header {
  display: flex;
  justify-content: space-between;
}
</style>
